// crypto.ts

import * as CryptoJS from 'crypto-js';
import { CRYPTO_JS_IV, CRYPTO_JS_KEY } from '../config/global';

// 加密函数
function encrypt(str: string): string {
    const key = CryptoJS.enc.Utf8.parse(CRYPTO_JS_KEY);
    const iv = CryptoJS.enc.Utf8.parse(CRYPTO_JS_IV);
    const encrypted = CryptoJS.AES.encrypt(str, key, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
}

// 解密函数
function decrypt(cipherText: string): any {
    const key = CryptoJS.enc.Utf8.parse(CRYPTO_JS_KEY);
    const iv = CryptoJS.enc.Utf8.parse(CRYPTO_JS_IV);
    const decrypted = CryptoJS.AES.decrypt(cipherText, key, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    const data = decrypted.toString(CryptoJS.enc.Utf8);
    try {
        return JSON.parse(data);
    } catch (e) {
        return data;
    }
}

export {
    encrypt,
    decrypt
};